
import UIKit

class KZHCountdownView: UIView {
    
    // 定时器
    fileprivate var codeTimer:DispatchSourceTimer?
    // 是否启动定时器
    var isStartTimer = true
    
    // MARK: - 共有
    // MARK: -- 结束时间（传递接口返回的时间戳）
    open var endTime:Double? {
        didSet {
            if isStartTimer == true {
                if codeTimer != nil { return }
                
                let queue = DispatchQueue.global()
                codeTimer = DispatchSource.makeTimerSource(queue: queue)
                codeTimer?.schedule(wallDeadline: .now(), repeating: .seconds(1))
                codeTimer?.setEventHandler { [weak self] in
                    DispatchQueue.main.async(execute: {
                        self?.refreshTime()
                    })
                }
                codeTimer?.resume()
            } else {
                refreshTime()
            }
        }
    }

    open var labelColor:UIColor? {
        didSet {
            guard let labelColor = labelColor else { return }
            labelTimer.backgroundColor = labelColor
        }
    }
    
    // MARK: -- 数字Label字体颜色
    open var labelTextColor:UIColor? {
        didSet {
            guard let labelTextColor = labelTextColor else { return }
            labelTimer.textColor = labelTextColor
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    
    convenience init(frame: CGRect, isStartTimer:Bool = true) {
        self.init(frame: frame)
        self.isStartTimer = isStartTimer
    }
    
    fileprivate func setupUI() {
        addSubview(labelTimer)
        self.labelColor = UIColor.white
        self.labelTextColor = UIColor.black
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        labelTimer.frame = self.bounds
    }
    
    // MARK: - 主要实现计算时间差值方法
    @objc func refreshTime() {
        guard let endTime = endTime else { return }
        let nowDate = Date.getCurrentDate()
        let endDate = endTime.timestampWithDate()
        let calendar = NSCalendar.current
        let components = calendar.dateComponents([.hour, .minute, .second], from: nowDate, to: endDate)
        guard let hour = components.hour,
            let minute = components.minute,
            let second = components.second else { return }

        if hour < 0 || minute < 0 || second < 0  {
            removeTimer()
             labelTimer.text = "0"
        }else{
            labelTimer.text = "\(hour.keepInt())" + ":" + "\(minute.keepInt())" + ":" +  "\(second.keepInt())"
        }
        
    }
    
    private lazy var labelTimer: UILabel = {
        let labelTimer = UILabel()
        labelTimer.textAlignment = .center
        return labelTimer
    }()
    
    // MARK: - 移除Timer
    fileprivate func removeTimer() {
        if codeTimer != nil {
            codeTimer?.cancel()
            codeTimer = nil
        }
    }

    deinit {
        removeTimer()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
